package com.blog4j.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog4j.api.vo.UserInfoVo;
import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.enums.UserStatusEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.user.entity.FansEntity;
import com.blog4j.user.entity.UserEntity;
import com.blog4j.user.mapper.FansMapper;
import com.blog4j.user.mapper.UserMapper;
import com.blog4j.user.service.FansService;
import com.blog4j.user.vo.req.FansListReqVo;
import com.blog4j.user.vo.resp.FansRespVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/8/1 13:34
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FansServiceImpl extends ServiceImpl<FansMapper, FansEntity>
        implements FansService {
    private final UserMapper userMapper;

    /**
     * 根据用户ID获取用户的粉丝信息列表
     *
     * @param reqVo 请求信息
     * @return 用户的粉丝信息列表
     */
    @Override
    public PageInfo<FansRespVo> pageList(FansListReqVo reqVo) {
        Integer pageSize = reqVo.getPageSize();
        Integer pageNo = reqVo.getPageNo();
        String userId = reqVo.getUserId();
        UserEntity user = userMapper.selectById(userId);
        if (Objects.isNull(user)) {
            throw new Blog4jException(ErrorEnum.USER_NOT_EXIST_ERROR);
        }

        LambdaQueryWrapper<FansEntity> wrapper = new LambdaQueryWrapper<FansEntity>()
                .eq(FansEntity::getUserId, userId);
        Page<Object> page = PageHelper.startPage(pageNo, pageSize);
        List<FansEntity> fansList = this.baseMapper.selectList(wrapper);
        List<FansRespVo> fansRespVoList = this.handleFansList(fansList);
        PageInfo<FansRespVo> pageInfo = new PageInfo<>(fansRespVoList);
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    /**
     * 根据用户ID获取粉丝列表
     *
     * @param userId 用户ID
     * @return 粉丝列表
     */
    @Override
    public List<UserInfoVo> getFansListByUserId(String userId) {
        UserEntity user = userMapper.selectById(userId);
        if (Objects.isNull(user)) {
            throw new Blog4jException(ErrorEnum.USER_NOT_EXIST_ERROR);
        }

        LambdaQueryWrapper<FansEntity> wrapper = new LambdaQueryWrapper<FansEntity>()
                .eq(FansEntity::getUserId, userId);
        List<FansEntity> fansList = this.baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(fansList)) {
            return null;
        }
        Set<String> fansIdSet = fansList.stream().map(FansEntity::getFansId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserEntity> wrapper1 = new LambdaQueryWrapper<UserEntity>()
                .in(UserEntity::getUserId, fansIdSet)
                .orderByDesc(UserEntity::getCreateTime)
                .eq(UserEntity::getStatus, UserStatusEnum.NORMAL.getCode());
        List<UserEntity> userList = userMapper.selectList(wrapper1);
        if (CollectionUtil.isEmpty(userList)) {
            return null;
        }
        return userList.stream().map(item -> {
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(item, userInfoVo);
            return userInfoVo;
        }).collect(Collectors.toList());
    }

    private List<FansRespVo> handleFansList(List<FansEntity> fansList) {
        if (CollectionUtil.isEmpty(fansList)) {
            return new ArrayList<>();
        }

        Set<String> fansUserIdList = fansList.stream().map(FansEntity::getFansId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserEntity> wrapper1 = new LambdaQueryWrapper<UserEntity>()
                .in(UserEntity::getUserId, fansUserIdList);
        List<UserEntity> fansUserInfoList = userMapper.selectList(wrapper1);
        if (CollectionUtil.size(fansUserIdList) != CollectionUtil.size(fansUserInfoList)) {
            throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
        }

        List<FansRespVo> fansRespVoList = fansList.stream().map(item -> {
            FansRespVo fansRespVo = new FansRespVo();
            BeanUtils.copyProperties(item, fansRespVo);
            return fansRespVo;
        }).collect(Collectors.toList());

        for (FansRespVo fansRespVo : fansRespVoList) {
            String fansId = fansRespVo.getFansId();
            UserEntity userEntity = fansUserInfoList.stream().filter(item ->
                            StringUtils.equals(fansId, item.getUserId())).collect(Collectors.toList())
                    .get(0);
            fansRespVo.setFansUserName(userEntity.getUserName())
                    .setHomepageCover(userEntity.getHomepageCover());
        }
        return fansRespVoList;
    }
}
